package com.yangxd.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: yangxudong
 * @Date: 2021/4/20 18:00
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



    @Autowired
    private PasswordEncoder passwordEncoder;

    //    protected WebSecurityConfig() {
//        super();
//    }
  /*  @Bean
    public UserDetailsService myUserService(){
       // return new UserDetailsServiceImpl();
    }*/
    @Bean
    public PasswordEncoder passwordEncoder() {
        //使用hash加密方式
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);

       // auth.userDetailsService(myUserService()).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //  super.configure(web);
        //那些文件夹忽略，静态资源放行
        web.ignoring().antMatchers("/css/**","/js/**");



    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //
                //任何请求都需要认证
                .anyRequest().authenticated()

                .and()
                //设置登录页面
                .formLogin().loginPage("/login")
                //设置登录成功页面
                .defaultSuccessUrl("/success").permitAll()
                .and()
                //注销页面放行
                .logout().permitAll();

        //关闭防火墙
        http.csrf().disable();

    }
}
